import { Card, Input, Form, Button, Pagination, Table, message, Modal } from 'antd'
import React, { useEffect, useState } from 'react'
import { SearchOutlined, InfoCircleOutlined, DeleteOutlined, CheckOutlined, FormOutlined } from '@ant-design/icons'
import projectApi, { assignRolesModel } from '@/api/project'
import { ColumnsType } from 'antd/lib/table'
import Router from '@/router/Router'
export default function Role(props: any) {
  // 当前页
  const [current, setCurrent] = useState(1)
  // 每页数量
  const [pageSize, setPageSize] = useState(5)
  // 总数
  const [total, setTotal] = useState(0)
  // 用户名
  const [userName, setUserName] = useState('')
  // 角色列表
  const [roleList, setRoleList] = useState<assignRolesModel[]>([])
  // 已选择的行
  const [selectUser, setSelectUser] = useState<string[]>([])
  const [loading, setLoading] = useState(false)
  const [searchUserName, setSearchUserName] = useState('')
  // 控制单个修改名字
  const [isEdit, setIsEdit] = useState('')
  const [isAddUserShow, setIsAddUserShow] = useState(false)
  const [roleName, setRoleName] = useState('')
  // 修改页数
  const editPage = (current: number, pageSize: number) => {
    setCurrent(current)
    setPageSize(pageSize)
  }
  // 获取角色列表
  const reqRoleList = async () => {
    try {
      setLoading(true)
      let result = await projectApi.reqRoleList(current, pageSize, userName)
      result.items.forEach((item) => (item.isIpt = false))
      setRoleList(result.items)
      setTotal(result.total)
    } catch (error) {
      message.error(error)
    } finally {
      setLoading(false)
    }
  }
  useEffect(() => {
    reqRoleList()
  }, [current, pageSize, userName])
  const columns: ColumnsType<any> = [
    {
      width: '80px',
      title: '序号',
      render(a, b, index) {
        return index + 1
      }
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      render(text, row) {
        return !row.isIpt ? text : <Input value={isEdit} onChange={(e) => setIsEdit(e.target.value)} />
      }
    },
    {
      width: '300px',
      align: 'center',
      title: '操作',
      render(row) {
        return (
          <>
            <Form size="small" layout="inline">
              <Form.Item>
                <Button
                  onClick={() => {
                    props.history.push(`/acl/role/auth?id=${row.id}&roleName=${row.roleName}`)
                  }}
                  icon={<InfoCircleOutlined />}
                ></Button>
              </Form.Item>
              <Form.Item>
                <Button onClick={saveRoleName(row)} type="primary" icon={<CheckOutlined />}></Button>
              </Form.Item>

              <Form.Item>
                {!row.isIpt ? (
                  <Button
                    type="primary"
                    onClick={() => {
                      setIsEdit(row.roleName)
                      setRoleList(
                        roleList.map((item) => {
                          return {
                            ...item,
                            isIpt: item.id == row.id
                          }
                        })
                      )
                    }}
                    icon={<FormOutlined />}
                  ></Button>
                ) : (
                  <Button
                    onClick={() => {
                      setRoleList(
                        roleList.map((item) => {
                          return {
                            ...item,
                            isIpt: item.id == row.id && !item.isIpt
                          }
                        })
                      )
                    }}
                  >
                    取消
                  </Button>
                )}
              </Form.Item>

              <Form.Item>
                <Button onClick={deleteUser(row)} danger icon={<DeleteOutlined />}></Button>
              </Form.Item>
            </Form>
          </>
        )
      }
    }
  ]
  const rowSelection = {
    onChange: (selectedRowKeys: any[]) => {
      setSelectUser(selectedRowKeys)
    }
  }
  // 批量删除
  const deleteAllCheck = async () => {
    try {
      await Promise.all(
        selectUser.map((item) => {
          return new Promise(async (resolve, reject) => {
            try {
              await projectApi.deleteRole(item)
            } catch (error) {
            } finally {
              resolve('1')
              reqRoleList()
            }
          })
        })
      )
      message.success('删除成功')
    } catch (error) {}
  }
  // 单个删除
  const deleteUser = (role: assignRolesModel) => {
    return async () => {
      try {
        await projectApi.deleteRole(role.id!)
        message.success('删除成功')
      } catch (error) {
        message.error(error)
      } finally {
        reqRoleList()
      }
    }
  }
  const searchUser = () => {
    setUserName(searchUserName)
  }
  // 修改角色名称
  const saveRoleName = (role: assignRolesModel) => {
    return async () => {
      if (!role.isIpt) return
      delete role.isIpt
      try {
        await projectApi.saveRoleName({ ...role, roleName: isEdit })
        message.success('保存成功')
      } catch (error) {
        message.error(error)
      } finally {
        reqRoleList()
      }
    }
  }
  const addRole = async () => {
    try {
      console.log(1)

      await projectApi.addRole(roleName)
      message.success('保存成功')
    } catch (error) {
      message.error(error)
    } finally {
      setIsAddUserShow(false)
      reqRoleList()
    }
  }
  return (
    <>
      <Card>
        <Form style={{ marginBottom: 20 }} layout="inline">
          <Form.Item>
            <Input
              value={searchUserName}
              onInput={(e) => setSearchUserName((e.target as any).value)}
              placeholder="用户名"
            />
          </Form.Item>
          <Form.Item>
            <Button shape="round" type="primary" onClick={searchUser} icon={<SearchOutlined />}>
              查找
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              shape="round"
              onClick={() => {
                setUserName('')
              }}
            >
              清空
            </Button>
          </Form.Item>
        </Form>
        <div style={{ marginBottom: 20 }}>
          <Button
            onClick={() => {
              setIsAddUserShow(true)
            }}
            shape="round"
            style={{ marginRight: 20 }}
            type="primary"
          >
            添加
          </Button>
          <Button onClick={deleteAllCheck} shape="round" disabled={!selectUser.length} danger>
            批量删除
          </Button>
        </div>
        <Table
          pagination={false}
          loading={loading}
          bordered
          rowSelection={rowSelection}
          rowKey="id"
          columns={columns}
          dataSource={roleList}
          style={{ marginBottom: 20 }}
        ></Table>
        <Pagination
          showQuickJumper
          current={current}
          defaultCurrent={current}
          defaultPageSize={pageSize}
          total={total}
          pageSizeOptions={['3', '5', '7']}
          onChange={editPage}
        />
      </Card>
      <Modal title={'添加角色'} onOk={addRole} onCancel={() => setIsAddUserShow(false)} open={isAddUserShow}>
        <div style={{ marginBottom: 20 }}>请输入新名称</div>
        <Input
          value={roleName}
          onInput={(e) => {
            setRoleName((e.target as any).value)
          }}
        />
      </Modal>
    </>
  )
}
